package org.restorator.di;

import org.restorator.exception.ServiceLocatorException;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author Snisar Bogdan.
 */
public final class ServiceLocator {

    final ServiceFactory factory;

    private static final ServiceLocator INS = new ServiceLocator();

    public static ServiceLocator create() {
        return INS;
    }

    private ServiceLocator() {
        ServiceBuilder builder = new ServiceBuilder();
        InitialContext contx = new InitialContext(builder);
        contx.parse();
        factory = new ServiceFactory(builder);
    }

    public Object create(String key) {
        return create0(key, Object.class);
    }

    public <E> E create(String key, Class<E> type) {
        return create0(key, type);
    }

    private  <E> E create0(String key, Class<E> clazz){
        try {
            return clazz.cast(factory.get(key));
        } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) {
            throw new ServiceLocatorException("exception in object creation", e);
        }
    }

}
